package com.wyw.hemerocallis;

import com.wyw.hemerocallis.permission.OpModeEnum;
import com.wyw.hemerocallis.permission.PermissionClient;
import com.wyw.hemerocallis.permission.vo.CreatePathRequest;
import com.wyw.hemerocallis.vo.CommonResponse;
import com.wyw.hemerocallis.vo.PermissionInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限注册组件
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
public class PermissionRegistry {

    private PermissionClient permissionClient;

    private String serviceName;

    PermissionRegistry(PermissionClient permissionClient, String serviceName) {
        this.permissionClient = permissionClient;
        this.serviceName = serviceName;
    }

    /**
     * 权限注册
     */
    boolean register(List<PermissionInfo> infoList) {
        if(CollectionUtils.isEmpty(infoList)) {
            return false;
        }
        List<CreatePathRequest.PathInfo> pathInfos = infoList.stream()
                .map(info -> CreatePathRequest.PathInfo.builder()
                .pathPattern(info.getUrl())
                .httpMethod(info.getMethod())
                        .pathName(info.getDescription())
                        .serviceName(serviceName)
                        .opMode(info.getIsRead() ? OpModeEnum.READ.getMode() : OpModeEnum.WRITE.getMode()).build()
                ).collect(Collectors.toList());

        CommonResponse<List<Integer>> response =
                permissionClient.createPath(new CreatePathRequest(pathInfos));

        if(!CollectionUtils.isEmpty(response.getData())) {
            log.info("register path info: {}", response.getData());
            return true;
        }
        return false;
    }

}
